<template>
  <div ref="content" class="content">
    <el-form
      ref="queryForm"
      :model="defaultData"
      size="small"
      class="form-block"
      :inline="true"
      :dict-list="listTypeInfo"
      :label-width="labelWidth"
      @submit.native.prevent>
      <template v-for="(item, index) in fieldList">
        <div v-if="!item.hidden" :key="index">
          <div class="item-style">
            <el-form-item :label="item.label">
              <!--插槽-->
              <template v-if="item.type === 'slot'">
                <slot :name="'filter-' + item.field" />
              </template>
              <!-- 普通输入框 -->
              <!-- @keyup.enter.native="handleSearch"  -->
              <el-input
                v-if="item.type === 'input' && !item.hidden"
                v-model.trim="defaultData[item.field]"
                :type="item.type"
                :clearable="true"
                :disabled="item.disabled"
                :maxlength="item.maxlength"
                :style="{ width: item.width }"
                :show-word-limit="item.showWordLimit"
                :placeholder="item.placeholder || getPlaceholder(item)"
                @clear="handleEvent($event, item.field)"
                @blur="handleEvent($event, item.field)"
                @keyup.enter.native="handleSearch" />
              <!-- 日期选择器 -->
              <el-date-picker
                v-if="item.type === 'date'"
                v-model="defaultData[item.field]"
                :type="item.dateType"
                :picker-options="item.TimePickerOptions"
                :clearable="true"
                :disabled="item.disabled"
                :default-time="item.defaultTime"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :placeholder="getPlaceholder(item)"
                @change="handleEvent($event, item.field, 'change')" />
              <!-- 日期时间选择器 -->
              <el-date-picker
                v-if="item.type === 'datetime'"
                v-model="defaultData[item.field]"
                type="datetime"
                :picker-options="item.TimePickerOptions"
                :clearable="true"
                :disabled="item.disabled"
                :default-time="item.defaultTime"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="请选择日期时间"
                @change="handleEvent($event, item.field, 'change')" />
              <!--日期区间选择器-->
              <el-date-picker
                v-if="item.type == 'dateRange'"
                v-model="defaultData[item.field]"
                style="width: 100%"
                :value-format="item.format || 'yyyy-MM-dd HH:mm:ss'"
                :default-time="['00:00:00', '23:59:59']"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="item.TimePickerOptions"
                @change="handleEvent($event, item.field, 'change')" />
              <!-- 日期时间区间选择器 -->
              <el-date-picker
                v-if="item.type == 'datetimerange'"
                v-model="defaultData[item.field]"
                style="width: 100%"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleEvent($event, item.field, 'change')" />
              <!-- 选择框 -->
              <el-select
                v-if="item.type === 'select'"
                v-model="defaultData[item.field]"
                :disabled="item.disabled"
                :clearable="true"
                filterable
                :multiple="item.multiple"
                :placeholder="getPlaceholder(item)"
                :style="{ width: item.width }"
                @clear="handleEvent($event, item.field, 'change')"
                @change="handleEvent($event, item.field, 'change')">
                <el-option
                  v-for="(childItem, childIndex) in listTypeInfo[item.list]"
                  :key="childIndex"
                  :label="childItem.label"
                  :value="setBindValue(childItem)"
                  :disabled="childItem.disabled" />
              </el-select>
              <!-- 级联选择器 -->
              <el-cascader
                v-if="item.type === 'cascader'"
                ref="cascader"
                v-model="defaultData[item.field]"
                filterable
                :options="listTypeInfo[item.list]"
                :props="item.props"
                :show-all-levels="false"
                clearable
                :style="{ width: item.width }"
                :collapse-tags="item.collapseTag"
                @expand-change="expandChange"
                @change="
                  isAsset == true ? handleAsset($event, item, 'change') : handleEvent($event, item.field, 'change')
                " />
              <!-- 计数器 -->
              <el-input-number
                v-if="item.type === 'inputNumber'"
                v-model="defaultData[item.field]"
                controls-position="right"
                :min="item.min"
                :max="item.max"
                @change="handleEvent($event, item.field, 'change')" />
            </el-form-item>
          </div>
        </div>
      </template>
    </el-form>
    <div v-if="!btnHidden" style="margin-right: 20px;padding-bottom: 5px;">
      <el-button
        type="primary"
        size="mini"
        icon="el-icon-search"
        :disabled="defaultData.searchBtn"
        @click="handleSearch"
        >查询</el-button
      >
      <el-button
        class="bt-class"
        size="mini"
        icon="el-icon-refresh"
        :disabled="defaultData.resetBtn"
        @click="handleReset"
        >重置</el-button
      >
    </div>

    <div class="downBtn">
      <slot name="downBtn" />
    </div>
    <!--    <div
      v-if="fieldList.length > colCount"
      :class="['semicircle', icon === 'close' ? 'down' : '']"
      @click="icon === 'open' ? (icon = 'close') : (icon = 'open')"
    >
      <i class="el-icon-arrow-up"/>
    </div>-->
  </div>
</template>
<script>
export default {
  name: 'SearchForm',
  props: {
    // 是否是级联
    isAsset: {
      type: Boolean,
      default: false,
    },
    /** laberl宽度设置 */
    labelWidth: {
      type: String,
      default: '100px',
    },
    /** 字段默认数据 */
    data: {
      type: Object,
      default: () => {},
    },
    /** 字段配置项 */
    fieldList: {
      type: Array,
      default: () => [],
    },
    /** 相关的列表 */
    listTypeInfo: {
      type: Object,
      default: () => {},
    },
    /** 是否隐藏操作按钮 */
    btnHidden: {
      type: Boolean,
      default: false,
    },
    /** searchBtn 是否禁用 */
    searchBtn: {
      type: Boolean,
      default: false,
    },
    /** 重置按钮 */
    resetBtn: {
      type: Boolean,
      default: false,
    },
    /** 搜索数量 */
    count: {
      type: [Number, String],
      default: 4,
    },
    isNeedResetExtraParam: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      icon: 'close',
      colCount: null, // 每行的列数量
      defaultKeyList: [], // 组件内置操作框key数组，用于watch更新
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
      },
    }
  },
  computed: {
    defaultData: {
      get() {
        return this.data
      },
    },
  },
  // watch: {
  //   data: {
  //     handler(val) {
  //       console.log('事件触发------')
  //       for (const key in val) {
  //         this.$set(this.defaultData, key, val[key])
  //       }
  //       // const resolveVal = cloneDeep(val)
  //       // for (const key in resolveVal) {
  //       //   if (resolveVal[key] !== null) {
  //       //     // if (this.defaultKeyList.indexOf(key) > 0) {
  //       //     this.defaultData[key] = cloneDeep(resolveVal[key])
  //       //     // }
  //       //   }
  //       // }
  //     },
  //     deep: true,
  //     immediate: true
  //   }
  // },

  mounted() {
    /**
     * 子组件无法直接修改父组件传递过来的值
     * 于是将父组件传递的值首先赋值给 defaultData
     * 在搜索条件中同样使用 defaultData
     * 永远保持 props 传递的 data 纯洁度
     */
    this.setColCount()
    // window.addEventListener('resize', this.setColCount);
  },

  beforeDestroy() {
    // window.removeEventListener('resize', this.setColCount);
  },

  methods: {
    // 解决级联选死机问题
    expandChange() {
      this.$nextTick(() => {
        // 添加这段代码
        const $el = document.querySelectorAll('.el-cascader-panel .el-cascader-node[aria-owns]')
        Array.from($el).map((item) => item.removeAttribute('aria-owns'))
      })
    },
    /**
     * 设置 每行的列数量
     */
    setColCount() {
      const ref = this.$refs.content
      const styleAttr = window.getComputedStyle(ref, null)
      const width = Number.parseInt(styleAttr['width'])
      const pl = Number.parseInt(styleAttr['padding-left'])
      const pr = Number.parseInt(styleAttr['padding-right'])
      // 332 每个输入组件 宽度332 暂时写死
      this.colCount = Math.ceil((width - pl - pr) / 332)
    },
    setvalueModel(val) {
      return val
    },
    /**
     * 设置 绑定select 的值
     */
    setBindValue(item) {
      const value = item?.value ?? item?.id
      return value
    },
    /**
     * @func 占位符显示
     * @param {Object} row
     * @desc 📝
     */
    getPlaceholder(row) {
      let placeholder
      if (row.label) {
        if (row.type === 'input') {
          placeholder = '请输入' + row.label
        } else if (row.type === 'select' || row.type === 'time' || row.type === 'date') {
          placeholder = '请选择' + row.label
        } else {
          placeholder = row.label
        }
      } else {
        if (row.type === 'input') {
          placeholder = '请输入'
        } else if (row.type === 'select' || row.type === 'time' || row.type === 'date') {
          placeholder = '请选择'
        }
      }
      return placeholder
    },
    /**
     * @func 事件处理
     * @desc 📝
     */
    handleEvent(event, val, change) {
      let obj = {}
      if (event) {
        this.defaultKeyList.indexOf(val) < 0 && this.defaultKeyList.push(val)
        obj = {
          value: change === 'change' ? event : event.target.value,
          field: val,
        }
      } else {
        obj = {
          value: null,
          field: val,
        }
        this.defaultData[val] = obj.value
      }

      this.$emit('handleEvent', obj)
    },
    /**
     * @func 资产管理级联事件处理
     * @desc 📝
     */
    handleAsset(event, val, change) {
      const nodesInfo = this.$refs.cascader[0].getCheckedNodes()[0].data
      this.$emit('handleInfo', nodesInfo)
    },

    /**
     * @func 搜索
     * @desc 📝
     */
    handleSearch() {
      this.$emit('handleSearch', this.defaultData)
    },

    /**
     * @func 重置
     * @desc 📝
     */
    handleReset() {
      // 防止重置额外参数
      if (this.isNeedResetExtraParam) {
        this.fieldList.forEach((o) => (this.defaultData[o.field] = null))
      } else {
        for (const key in this.defaultData) {
          this.defaultData[key] = null
        }
      }
      this.$emit('handleReset', this.defaultData)
    },
  },
}
</script>
<style lang="scss" scoped>
.downBtn{
  text-align: right;
  margin-top: 20px;
  padding-bottom: 5px;
}
.el-input,
.el-select,
.el-date-editor,
.el-cascader,
.el-autocomplete,
.el-input-number {
  width: 220px;
}

.el-form-item__label {
  display: block;
}

.content {
  padding-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  position: relative;
  align-items: flex-end;

  .item-style {
    margin: 0 auto;
    line-height: 1;
    display: flex;
    align-items: center;

    .label-style {
      display: inline-block;
      justify-self: end;
      width: 100px;
      font-size: 13px;
      white-space: nowrap;
      overflow: hidden;
      -o-text-overflow: ellipsis;
      text-overflow: ellipsis;
      text-align: right;
      margin-right: 12px;
      color: #222222;
    }
  }

  // &:hover .semicircle {
  //     display: block;
  // }

  .semicircle {
    display: block;
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 36px;
    height: 16px;
    text-align: center;
    color: #999999;
    background-color: #ffffff;
    box-shadow: 0px -3px 8px 0px rgba(29, 58, 102, 0.08);
    border: 1px solid #e8e8e8;
    border-radius: 100px 100px 0 0;

    &:hover {
      cursor: pointer;
      color: #409eff;
    }
  }

  .down {
    bottom: -16px;
    border-radius: 0 0 100px 100px;

    & > i {
      position: absolute;
      left: -1px;
      right: 0;
      top: -3px;
      margin: auto;
      transform: rotate(180deg);
    }
  }

  .form-block {
    //flex:1;
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 5px;
  }
}
</style>
